# -*- coding: utf-8-*-
import os
import base64
import tempfile
import pypinyin
from aip import AipSpeech
from . import constants, utils
from pathlib import Path
from pypinyin import lazy_pinyin
from pydub import AudioSegment
from abc import ABCMeta, abstractmethod


class BaiduTTS(object):
    """
    使用百度语音合成技术
    要使用本模块, 首先到 yuyin.baidu.com 注册一个开发者账号,
    之后创建一个新应用, 然后在应用管理的"查看key"中获得 API Key 和 Secret Key
    填入 config.yml 中.
    ...
        baidu_yuyin: 
            appid: '9670645'
            api_key: 'qg4haN8b2bGvFtCbBGqhrmZy'
            secret_key: '585d4eccb50d306c401d7df138bb02e7'
            dev_pid: 1936
            per: 1
            lan: 'zh'
        ...
    """

    def __init__(self, appid, api_key, secret_key, per=0, lan='zh', **args):
        self.client = AipSpeech(appid, api_key, secret_key)
        self.per, self.lan = str(per), lan

    def get_speech(self, phrase):
        result = self.client.synthesis(phrase, self.lan, 1, {'per': self.per})
        # 识别正确返回语音二进制 错误则返回dict 参照下面错误码
        if not isinstance(result, dict):
            tmpfile = utils.write_temp_file(result, '.mp3')
            print('语音合成成功，合成路径：{}'.format(tmpfile))
            return tmpfile
        else:
            print('合成失败！', exc_info=True)
